package com.lfk.justwetools.Utils;

import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.app.Context;
import ohos.miscservices.timeutility.Timer;

/**
 * Created by liufengkai on 15/10/19.
 */
public class AlarmUtil {

    private static String CODE = "intent_code";

    private static Timer.OneShotTimer oneShotTimer = null;

    /**
     * 指定时间后进行更新
     * 注意: Receiver 记得在注册
     *
     * @param context
     */
    public static void sendUpdateBroadcast(Context context, int time, String code) {
        Intent intent = new Intent();
        Operation operation = new Intent.OperationBuilder().withAction(CODE).build();
        intent.setParam("code", code);
        intent.setOperation(operation);
        Timer.TimerIntent timerIntent = new Timer.TimerIntent(intent, Timer.ABILITY_TYPE_COMMON_EVENT);
        Timer.OneShotTimer timer = Timer.OneShotTimer.getTimer(context, timerIntent);
        // 60秒后将产生广播,触发UpdateReceiver的执行,这个方法才是真正的更新数据的操作主要代码
        timer.start(Timer.TIMER_TYPE_REALTIME, System.currentTimeMillis() + time*1000);
        oneShotTimer = timer;
    }

    /**
     * 取消定时执行
     *
     * @param context
     */
    public static void cancelUpdateBroadcast(Context context) {
        if (oneShotTimer != null) {
            oneShotTimer.stop();
        }
    }
}
